package com.jt.assistant.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.ToastUtils
import com.cl.picture_selector.ImagePicker
import com.google.gson.reflect.TypeToken
import com.jt.assistant.R
import com.jt.assistant.adapter.DialogListAdapter
import com.jt.assistant.adapter.DiffAdapter
import com.jt.assistant.adapter.PicAdapter
import com.jt.assistant.base.GlobalConfig
import com.jt.assistant.base.GlobalConfig.SCAN_TYPE
import com.jt.assistant.base.GlobalConfig.SCAN_TYPE_RECEIVE
import com.jt.assistant.bean.DiffSkuListBean
import com.jt.assistant.bean.Param
import com.jt.assistant.bean.SkuListBean
import com.jt.assistant.custom_view.ItemEdit
import com.jt.assistant.utils.BasisTimesUtils
import com.jt.assistant.utils.GlideLoader
import com.jt.assistant.viewmodel.HomeViewModel
import com.orhanobut.logger.Logger
import com.yzp.mvvmlibrary.base.BaseActivity
import com.yzp.mvvmlibrary.base.MessageEvent
import kotlinx.android.synthetic.main.activity_receive.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import java.io.File
import java.util.*
import kotlin.collections.ArrayList

/**
 * 验收单登记
 */
class ReceiveActivity : BaseActivity<HomeViewModel>() {
    private val mAdapter by lazy {
        PicAdapter(
            ArrayList<String>()
        )
    }
    private val mDiffAdapter by lazy {
        DiffAdapter(
            ArrayList<DiffSkuListBean>()
        )
    }
    val mSkuList = ArrayList<SkuListBean>()
    private val maxPicCount = 30//最大图片选择数量
    private var type = "2"

    override fun onDestroy() {
        set_scan.unregisterEventBus()
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }

    override fun layoutId(): Int = R.layout.activity_receive

    override fun initView(savedInstanceState: Bundle?) {
        with(rv_receive) {
            layoutManager = GridLayoutManager(context, 3)
            canScrollVertically(0)
            adapter = mAdapter
            mAdapter.data.add("")
            mAdapter.notifyDataSetChanged()
        }
        with(rv_diff) {
            layoutManager = LinearLayoutManager(context)
            adapter = mDiffAdapter
        }

        set_scan.initCamera(this, GlobalConfig.SCAN_TYPE_ONESHOT)
        EventBus.getDefault().register(this)
    }

    override fun initData() {
        ie_diff.mData.add("不存在")
        ie_diff.mData.add("存在")
        ie_diff.setEditText("不存在")
        ie_time.mEdit.setText(BasisTimesUtils.getDeviceTimeOfYMD())

        if (!intent.getStringExtra("CHANNELORDERNO").isNullOrEmpty()) {
            ie_ReceiveCode.mEdit.setText(intent.getStringExtra("CHANNELORDERNO").toString())
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun message(messageEvent: MessageEvent) {
        if (messageEvent.type == SCAN_TYPE_RECEIVE) {
            this@ReceiveActivity.ie_ReceiveCode.mEdit.setText(messageEvent.msg)
        }
    }

    override fun initListener() {
        netListener()

        tv_chooseSku.setOnClickListener {
            showListDialog()
        }

        iv_scan.setOnClickListener {
            val intent = Intent(this, DecodeActivity::class.java)
            intent.putExtra(SCAN_TYPE, SCAN_TYPE_RECEIVE)
            startActivity(intent)
        }

        ie_diff.mEdit.setOnClickListener {
            ie_diff.showListDialog("是否存在差异", this)
        }

        ie_diff.setOnItemClickListener(object : ItemEdit.OnClickLister {
            override fun onItemClick(position: Int) {
                if (position == 0) {//不存在
                    cd_diff.visibility = View.GONE
                    rv_diff.visibility = View.GONE
                    ie_diffRemark.visibility = View.GONE
                } else {//存在
                    val params = Param::class.java.newInstance()
                    params.channelOrderNo = ie_ReceiveCode.mEdit.text.toString()
                    viewModel.getSkuListByWaybill(params) //请求差异数据,请求成功之后更新数据
                }
            }
        })

        bt_addDiff.setOnClickListener {
            if (set_scan.string.isEmpty()) {
                ToastUtils.showShort("请扫入SKU码")
                set_scan.clearData()
                return@setOnClickListener
            }

//            mDiffAdapter.data.forEach {
//                if (set_scan.string == it.sku) {
//                    ToastUtils.showShort("请勿重复添加")
//                    set_scan.clearData()
//                    return@setOnClickListener
//                }
//            }

            if (et_skuNum.text.toString().isEmpty() || et_skuNum.text.toString() == "0") {
                ToastUtils.showShort("数量异常")
                return@setOnClickListener
            }

            mDiffAdapter.data.add(
                DiffSkuListBean(
                    et_skuNum.text.toString(),
                    type,
                    set_scan.string
                )
            )
            mDiffAdapter.notifyDataSetChanged()
            set_scan.clearData()
            et_skuNum.setText("")
        }

        ie_time.mEdit.setOnClickListener {
            showYearMonthDayPicker()
        }

        mDiffAdapter.setOnItemClickListener { adapter, view, position ->
            showTipDialog("是否删除${mDiffAdapter.data[position].sku}?", position)
        }

        mAdapter.setOnItemClickListener { adapter, view, position ->
            if (mAdapter.data[position].isEmpty()) {
                ImagePicker.getInstance()
                    .setTitle("标题") //设置标题
                    .showCamera(true) //设置是否显示拍照按钮
                    .showImage(true) //设置是否展示图片
                    .showVideo(true) //设置是否展示视频
                    .showLoading(true, "请稍后...")
                    .setMaxCount(maxPicCount - mAdapter.itemCount + 1) //设置最大选择图片数目(默认为1，单选)
                    .setSingleType(true) //设置图片视频不能同时选择
                    .setImageLoader(GlideLoader()) //设置自定义图片加载器
                    .start(
                        this@ReceiveActivity,
                        GlobalConfig.REQUEST_SELECT_IMAGES_CODE
                    ) //REQEST_SELECT_IMAGES_CODE为Intent调用的requestCode
            } else {//预览图
                startActivityForResult(Intent(this@ReceiveActivity, PreActivity::class.java).apply {
                    putExtra("IMAGEPATH", GsonUtils.toJson(mAdapter.data))
                    putExtra("POSITION", position)
                }, GlobalConfig.PIC_REQUEST)
            }

        }

        rg_receive.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.rb_duo -> {
                    type = "2"
                }
                R.id.rb_shao -> {
                    type = "1"
                }
                R.id.rb_bad -> {
                    type = "3"
                }
            }
        }

        bt_commit.setOnClickListener {
            if (ie_ReceiveCode.mEdit.text.toString().isEmpty()) {
                ToastUtils.showShort("请输入渠道单号")
                return@setOnClickListener
            }
            if (mAdapter.data.size == 1) {
                ToastUtils.showShort("请选择图片")
                return@setOnClickListener
            }
            if (ie_diff.mCurrentPosition == 1 && ie_diffRemark.mEdit.text.isEmpty()) {//存在差异
                ToastUtils.showShort("请输入差异备注")
                return@setOnClickListener
            }
            if (ie_diff.mCurrentPosition == 1 && mDiffAdapter.data.isEmpty()) {//存在差异
                ToastUtils.showShort("请选择差异项")
                return@setOnClickListener
            }

            val params = Param::class.java.newInstance()
            params.hasDiff = ie_diff.mCurrentPosition.toString()
            params.channelOrderNo = ie_ReceiveCode.mEdit.text.toString()
            params.jdDate = ie_time.mEdit.text.toString()
            if (ie_diff.mCurrentPosition == 1) {//存在差异
                params.remark = ie_diffRemark.mEdit.text.toString()
                params.diffSkuList = mDiffAdapter.data
            }
            viewModel.uploadJdReceiveReport(params, mAdapter.data)
        }

    }

    private fun netListener() {
        viewModel.mGetSkuListByWaybill.observe(this, {
            log(it)
            if (it.isSuccess()) {
                if (it.data.size == 0) {
                    ToastUtils.showShort("没有SKU码")
                    cd_diff.visibility = View.GONE
                    rv_diff.visibility = View.GONE
                    ie_diffRemark.visibility = View.GONE
                    this@ReceiveActivity.ie_diff.setCurrentPosition(0)
                    return@observe
                }

                mSkuList.clear()
                mSkuList.addAll(it.data)
                cd_diff.visibility = View.VISIBLE
                rv_diff.visibility = View.VISIBLE
                ie_diffRemark.visibility = View.VISIBLE

            } else {
                this@ReceiveActivity.ie_diff.setCurrentPosition(0)
            }
        })

        viewModel.mUploadJdReceiveReport.observe(this, {
            log(it)
            if (it.isSuccess()) {
                speakString("上传成功")
                finish()
            }
        })
    }

    private fun showListDialog() {
        val dialog = MaterialDialog(this@ReceiveActivity).show {
            title(text = "请选择SKU")
            customView(R.layout.layout_dialog_list, scrollable = true, horizontalPadding = false)
            lifecycleOwner(this@ReceiveActivity)
        }
        // Setup custom view content
        val customView = dialog.getCustomView()
        val rvDialog: RecyclerView = customView.findViewById(R.id.rv_dialog)
        val listAdapter = DialogListAdapter(ArrayList<String>())
        with(rvDialog) {
            layoutManager = LinearLayoutManager(context)
            adapter = listAdapter
            mSkuList.forEach {
                listAdapter.data.add(it.sku)
            }
            listAdapter.notifyDataSetChanged()
        }
        listAdapter.setOnItemClickListener { adapter, view, position ->
            set_scan.string = listAdapter.data[position]
            dialog.dismiss()

        }
    }


    private fun showTipDialog(title: String, position: Int) {
        MaterialDialog(this).show {
            title(text = title)
            positiveButton(text = "确定删除") {
                mDiffAdapter.data.removeAt(position)
                mDiffAdapter.notifyDataSetChanged()
            }
            negativeButton(text = "取消") {}
            lifecycleOwner(this@ReceiveActivity)
        }
    }

    private fun showYearMonthDayPicker() {
        val calendar = Calendar.getInstance()
        BasisTimesUtils.showDatePickerDialog(this@ReceiveActivity,
            BasisTimesUtils.THEME_HOLO_DARK,
            "请选择年月日",
            calendar[Calendar.YEAR],
            calendar[Calendar.MONTH] + 1,
            calendar[Calendar.DATE],
            object : BasisTimesUtils.OnDatePickerListener {
                @SuppressLint("SetTextI18n")
                override fun onConfirm(year: Int, month: Int, dayOfMonth: Int) {
                    ie_time.mEdit.setText(
                        "$year-" + String.format(
                            "%02d",
                            month
                        ) + "-" + String.format("%02d", dayOfMonth)
                    )
                    showTimePick()
                }

                override fun onCancel() {}
            })
    }


    private fun showTimePick() {
        BasisTimesUtils.showTimerPickerDialog(this@ReceiveActivity, "请选择时分",
            Calendar.getInstance()[Calendar.HOUR_OF_DAY],
            Calendar.getInstance()[Calendar.MINUTE], true,
            object : BasisTimesUtils.OnTimerPickerListener {
                @SuppressLint("SetTextI18n")
                override fun onConfirm(hourOfDay: Int, minute: Int) {
                    ie_time.mEdit.setText(
                        ie_time.mEdit.text.toString() + String.format(
                            " %02d",
                            hourOfDay
                        ) + ":" + String.format("%02d", minute) + ":00"
                    )
                }

                override fun onCancel() {
                    ToastUtils.showShort("请选择时间")
                    showTimePick()
                }
            })
    }


    private fun imagePick(mImagePaths: ArrayList<String>?) {
        Luban.with(this)
            .load<String>(mImagePaths)
            .ignoreBy(100)
//            .setTargetDir(ImageUtil.getPath())
            .setFocusAlpha(false)
            .filter { path -> !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif")) }
            .setCompressListener(object : OnCompressListener {
                override fun onStart() {}

                @SuppressLint("SetTextI18n")
                override fun onSuccess(file: File) {
                    Logger.e(file.absolutePath)
                    mAdapter.data.add(0, file.absolutePath)
                    mAdapter.notifyDataSetChanged()
                    if ((mAdapter.data.size - 1) == maxPicCount) {
                        mAdapter.data.remove("")
                        mAdapter.notifyDataSetChanged()
                    }
                }

                override fun onError(e: Throwable) {
                    e.printStackTrace()
                }
            }).launch()
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == GlobalConfig.REQUEST_SELECT_IMAGES_CODE && resultCode == RESULT_OK) {
            imagePick(data!!.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES))
        }
        if (requestCode == GlobalConfig.PIC_REQUEST && resultCode == RESULT_OK) {
            val picList = GsonUtils.fromJson<ArrayList<String>>(
                data!!.getStringExtra(GlobalConfig.PIC_RESULT),
                object : TypeToken<ArrayList<String>>() {}.type
            )
            imagePickPre(picList)
        }
    }

    private fun imagePickPre(picList: ArrayList<String>?) {
        mAdapter.data.clear()
        if (picList!!.isNotEmpty()) {
            mAdapter.data.addAll(picList)
        }
        mAdapter.data.add("")
        if ((mAdapter.data.size - 1) == maxPicCount) {
            mAdapter.data.remove("")
        }
        mAdapter.notifyDataSetChanged()
    }


}